package com.hulk.dryad.admin.security.token;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hulk.dryad.persistence.entity.SysUserModel;
import com.hulk.dryad.persistence.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * <p>
 *
 * @author kim
 * @date 2020/10/15
 */
@Component
public class AdminTokenManager implements TokenManager {

	@Autowired
	private SysUserService sysUserService;

	@Value("${token.bearer.timeout:600}")
	private Integer plusMinutes;
	@Override
	public String createToken(String username) {
		LocalDateTime expireTime =  LocalDateTime.now().plusMinutes(plusMinutes);
		String token = StrUtil.uuid();
		LambdaUpdateWrapper<SysUserModel> uw = Wrappers.<SysUserModel>lambdaUpdate()
				.set(SysUserModel::getToken, token)
				.set(SysUserModel::getTokenExpireTime, expireTime)
				.eq(SysUserModel::getUsername, username);
		sysUserService.update(uw);
		return token;
	}

	@Override
	public String getUserFromToken(String token) {
		LocalDateTime currentTime = LocalDateTime.now();
		LambdaQueryWrapper<SysUserModel> qw = Wrappers.<SysUserModel>lambdaQuery()
				.eq(SysUserModel::getToken, token)
				.gt(SysUserModel::getTokenExpireTime, currentTime);
		SysUserModel user = sysUserService.getOne(qw);
		if (user != null) {
			return user.getUsername();
		}
		return null;
	}

	@Override
	public void removeToken(String token) {

	}


}
